import { Tree, Checkbox, message, Skeleton } from 'antd';
import React, { useEffect, useState, forwardRef, useImperativeHandle } from 'react';

import '../styles/permissionTable.css';

import { SvgIcon } from '@/components/icon';
import userService from '@/api/services/userService';

import { DownOutlined, RightOutlined } from '@ant-design/icons';

import useWindowWidth from '@/hooks/event/use-window-width';
import { useUserInfo } from '@/store/userStore';

import uniqBy from 'lodash/uniqBy';

const { TreeNode } = Tree;

type Props = {
  onRoleRefresh?: () => void;
  initSelected?: [];
  roleSelected?: String;
};

const DatasetTree = forwardRef(
  ({ onRoleRefresh, initSelected = [], roleSelected = '' }: Props, ref) => {
    const { role: userRole } = useUserInfo();
    const [expandedKeys, setExpandedKeys] = useState<String[]>([]);

    const [sidebarItems, setSidebarItems] = useState([]);

    const [selectedRole, setSelectedRole] = useState([]);
    const [selectedRoleIds, setSelectedRoleIds] = useState([]);
    const [treeLoading, setTreeLoading] = useState(false);
    const [currentRoleSelected, setCurrentRoleSelected] = useState<String>('');

    const { isPc } = useWindowWidth();

    const [roleNameList, setRoleNameList] = useState<string[]>([]);
    const [displayRole, setDisplayRole] = useState({});
    const [roleItems, setRoleItems] = useState<any>([]);

    const [displayRoleList, setDisplayRoleList] = useState([]);

    useEffect(() => {
      const ids = selectedRole.map((role) => role?.id);
      setSelectedRoleIds(ids);
    }, [selectedRole]);

    useImperativeHandle(ref, () => ({
      getRoleList,
    }));

    const expandProcess = async (roleData: Role[]) => {
      const roles: Role[] = [];
      async function processItem(item: any) {
        roles.push(item);
        if (item?.children) {
          for (const child of item?.children) {
            await processItem(child);
          }
        }
      }
      for (const item of roleData) {
        await processItem(item);
      }
      setExpandedKeys(roles?.map((r: Role) => r?.id));
      return roles;
    };

    useEffect(() => {
      const role = sidebarItems.filter((item: any) => item?.code === roleSelected)?.[0];
      if (role) {
        console.log(roleSelected, displayRoleList);

        if (roleSelected != currentRoleSelected && isPc) {
          refreshSelectRole([]);
        }
        setCurrentRoleSelected(roleSelected);

        if (role?.code == 'admin') {
          const buildInRole = sidebarItems.filter(
            (item: any) => item?.is_built_in === true || item?.code == roleSelected,
          );
          setDisplayRoleList(buildInRole);
          expandProcess(buildInRole);
        } else {
          setDisplayRoleList([role]);
          expandProcess([role]);
        }
      } else if (roleSelected) {
        setDisplayRoleList([]);
        expandProcess([]);
      }
    }, [roleSelected, sidebarItems]);

    const getRoleList = async (newRole?: Role) => {
      let data: any = [];
      let roles: Role[] = [];
      try {
        setTreeLoading(true);
        const roleData = await userService.getRolePermissions();
        data = uniqBy(roleData, 'id');
        setSidebarItems(data);

        if (roleSelected) {
          const users = data.filter((item: any) => item?.code == roleSelected) || [];
          if (users?.length == 0) {
            setDisplayRoleList([]);
          } else if (users?.[0]?.code == 'admin') {
            setDisplayRoleList(
              data.filter((item: any) => item?.is_built_in == true || item?.name == selectedRole),
            );
          } else {
            setDisplayRoleList([users?.[0]]);
          }
        } else {
          setDisplayRoleList(data || []);
        }

        roles = await expandProcess(data);

        if (newRole) {
          if (isPc) {
            if (selectedRole.length >= 4) {
              // 如果 selectedRole 长度大于等于 4，替换掉最后一个元素
              refreshSelectRole([...selectedRole.slice(0, -1), newRole]);
            } else {
              // 否则直接添加新角色
              refreshSelectRole([...selectedRole, newRole]);
            }
          } else {
            const temp = [newRole];
            refreshSelectRole(temp);
          }
        } else if (selectedRole.length > 0) {
          const updateRole = selectedRole
            .map((selected) => roles.find((item) => item?.id === selected?.id))
            .filter((item) => item !== undefined);
          refreshSelectRole(updateRole);
        }
      } catch (error) {
        console.error('Error fetching role permissions:', error);
      } finally {
        setTreeLoading(false);
      }

      return { data, roles };
    };

    const refreshSelectRole = (data) => {
      onRoleRefresh && onRoleRefresh(data);
      setSelectedRole(data);
    };

    useEffect(() => {
      getRoleList().then((res) => {
        if (isPc) {
          const userData = res?.data?.filter((i) => i?.id == userRole?.id);
          if (initSelected.length > 0) {
            console.log(initSelected, res?.roles);
            const initRole = initSelected
              .map((selected) => res?.roles.find((item) => item?.id === selected?.id))
              .filter((item) => item !== undefined);
            refreshSelectRole(initRole);
          } else {
            refreshSelectRole(userData);
          }
        }
      });
    }, []);

    const renderTreeNodes = (data) => {
      return data?.map((item) => {
        if (item?.children && item?.children?.length > 0) {
          return (
            <TreeNode
              key={item?.id}
              title={
                <div
                  style={{
                    width: '100%',
                    justifyContent: 'space-between',
                    backgroundColor: selectedRoleIds?.includes(item?.id) ? '#F5F0FF' : 'unset',
                  }}
                  className="flex cursor-pointer items-center"
                >
                  <div
                    style={{
                      display: 'flex',
                      width: '100%',
                      paddingBottom: '5px',
                      // height: '30px', borderBottom: '1px solid #DEE0ED'
                    }}
                    onClick={() => {
                      setExpandedKeys((prevExpandedKeys) => {
                        if (prevExpandedKeys.includes(item?.id)) {
                          return prevExpandedKeys.filter((key) => key !== item?.id);
                        }
                        return [...prevExpandedKeys, item?.id];
                      });
                    }}
                  >
                    <div
                      style={{
                        paddingRight: '5px',
                        position: 'absolute',
                        left: '-20px',
                      }}
                    >
                      {expandedKeys.includes(item?.id) ? <DownOutlined /> : <RightOutlined />}
                    </div>
                    <div
                      style={{
                        background: '#2ABFB6',
                        color: 'white',
                        fontSize: '18px',
                      }}
                      className="flex h-[24px] w-[24px] items-center justify-center rounded-lg"
                    >
                      <SvgIcon icon="rj-park-solid--people" size={18} />
                    </div>
                    <div className="ml-4">{item.name}</div>
                  </div>
                  <div style={{ display: 'flex', right: 15, position: 'absolute' }}>
                    <Checkbox
                      className="role-check"
                      checked={selectedRoleIds?.includes(item?.id)}
                      onChange={(e) => {
                        console.log(e);
                        console.log(e.target.checked);
                        e.preventDefault();
                        e.stopPropagation();
                        if (e.target.checked) {
                          if (selectedRole.length > 3) {
                            message.warning('最多展示4个角色');
                            return;
                          }
                          if (isPc) {
                            const temp = [...selectedRole, item];
                            temp.sort((a, b) => b.permissions.length - a.permissions.length);
                            refreshSelectRole(temp);
                          } else {
                            const temp = [item];
                            refreshSelectRole(temp);
                          }
                        } else {
                          const temp = selectedRole.filter((i) => i?.id !== item?.id);
                          refreshSelectRole(temp);
                        }
                      }}
                    />
                  </div>
                </div>
              }
            >
              {renderTreeNodes(item?.children || [])}
            </TreeNode>
          );
        }
        return (
          <TreeNode
            key={item?.id}
            title={
              <div
                style={{
                  width: '100%',
                  justifyContent: 'space-between',
                  backgroundColor: selectedRoleIds?.includes(item?.id) ? '#F5F0FF' : 'unset',
                }}
                className="flex cursor-pointer items-center"
              >
                <div
                  style={{
                    display: 'flex',
                    width: '100%',
                    height: '30px',
                    // borderBottom: '1px solid #DEE0ED'
                  }}
                  onClick={() => {
                    console.log(item);
                    setExpandedKeys((prevExpandedKeys) => {
                      if (prevExpandedKeys.includes(item?.id)) {
                        return prevExpandedKeys.filter((key) => key !== item?.id);
                      }
                      return [...prevExpandedKeys, item?.id];
                    });
                  }}
                >
                  <div
                    style={{
                      background: '#2ABFB6',
                      color: 'white',
                      fontSize: '18px',
                    }}
                    className="flex h-[24px] w-[24px] items-center justify-center rounded-lg"
                  >
                    <SvgIcon icon="rj-park-solid--people" size={18} />
                  </div>
                  <div className="ml-4">{item.name}</div>
                </div>
                <div style={{ display: 'flex', right: 15, position: 'absolute' }}>
                  <Checkbox
                    className="role-check"
                    checked={selectedRoleIds?.includes(item?.id)}
                    onChange={(e) => {
                      console.log(e.target.checked);
                      e.preventDefault();
                      e.stopPropagation();
                      console.log(item);
                      if (e.target.checked) {
                        if (selectedRole.length > 3) {
                          message.warning('最多展示4个角色');
                          return;
                        }
                        if (isPc) {
                          const temp = [...selectedRole, item];
                          temp.sort((a, b) => b.permissions.length - a.permissions.length);
                          console.log(temp);
                          refreshSelectRole(temp);
                        } else {
                          const temp = [item];
                          refreshSelectRole(temp);
                        }
                      } else {
                        const temp = selectedRole.filter((i) => i?.id !== item?.id);
                        refreshSelectRole(temp);
                      }
                    }}
                  />
                </div>
              </div>
            }
          />
        );
      });
    };

    //   const onRoleChange = (key: string) => {
    //     console.log(key, sidebarItems, displayRole);
    // };

    //  useEffect(() => {
    //    if (roleNameList?.length > 1) {
    //      const updatedRoleItems = roleNameList.map((roleName, index) => ({
    //        key: roleName,
    //        label: roleName,
    //        children: (
    //          <Tree
    //            blockNode
    //            className="custome-treenode"
    //            expandedKeys={expandedKeys}
    //            switcherIcon={<div style={{ display: 'none' }} />}
    //          >
    //            {renderTreeNodes(displayRole?.[roleName])}
    //          </Tree>
    //        ),
    //      }));
    //      setRoleItems(updatedRoleItems);
    //    }
    //  }, [roleNameList, selectedRoleIds]);

    return (
      <div
        className="dataset-tree flex-grow overflow-y-auto"
        style={{
          margin: '20px 0',
          borderRadius: '0',
        }}
      >
        {treeLoading ? (
          <Skeleton style={{ padding: '20px 0' }} />
        ) : (
          // roleNameList?.length > 1
          // ?
          // <div style={{ padding: '5px 10px' }}>
          //   <Tabs defaultActiveKey={roleNameList?.[0]} items={roleItems} onChange={onRoleChange} />
          // </div>
          // :
          <Tree
            blockNode
            className="custome-treenode"
            expandedKeys={expandedKeys}
            switcherIcon={<div style={{ display: 'none' }} />}
          >
            {/* {renderTreeNodes(sidebarItems)} */}
            {renderTreeNodes(displayRoleList)}
          </Tree>
        )}
      </div>
    );
  },
);

export default DatasetTree;
